package qinqiu

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"time"
)

const (
	token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJuZXdhaC5jaGluYS1odWFmYW5nLmNuIiwiYXVkIjoibmV3YWguY2hpbmEtaHVhZmFuZy5jbiIsImlhdCI6MTY0MDA3MjI5NSwibmJmIjoxNjQwMDcyMjk1LCJleHAiOjE2NDA2NzcwOTUsImp0aSI6eyJpZCI6MSwidHlwZSI6ImFkbWluIn19.PtdH-A-5G8L2QQ3lrepmf-wRkwXophLfZTfYdaXjLxc"
	上传网址  = "https://******.******.*****/***/product/product/0"
)

var client *http.Client

// 发送GET请求
func A获取(网址 string) (map[string]interface{}, error) {
	dd := A获取网址基础数据(网址)
	var bd map[string]interface{}
	if err := json.Unmarshal(dd, &bd); err != nil {
		return nil, nil
	}
	bd = bd["data"].(map[string]interface{})
	return bd, nil
}

func A获取网址基础数据(网址 string) (字节数据 []byte) {
	rsp, err := client.Get(网址)
	if err != nil {
		return
	}
	defer rsp.Body.Close()
	字节数据, _ = ioutil.ReadAll(rsp.Body)
	return
}

func init() {
	client = &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			IdleConnTimeout:     3 * time.Minute,
			TLSHandshakeTimeout: 5 * time.Second,
			DialContext: (&net.Dialer{
				Timeout:   5 * time.Second,
				KeepAlive: 10 * time.Minute,
				DualStack: true,
			}).DialContext,
		},
	}
}

// 发送POST请求(JSON)
func 网络发送Json(url string, body interface{}) ([]byte, error) {
	//bodyStr, err := json.Marshal(body)
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	jsonEncoder.Encode(body)
	//fmt.Printf("\nstring%v", bf.String())
	return 网络发送(url, "application/json", bf.String())
}

// 发送POST请求(XML)
func HttpPostXml(url string, xmlBody string) ([]byte, error) {
	return 网络发送(url, "application/xml", xmlBody)
}

// 发送通用的POST请求
func 网络发送(url string, contentType string, body string) ([]byte, error) {
	rsp, err := client.Post(url, contentType, strings.NewReader(body))
	if err != nil {
		return nil, err
	}
	defer rsp.Body.Close()
	return ioutil.ReadAll(rsp.Body)
}

//这个是发表的
func NewPost(body interface{}) {
	byte1, _ := json.Marshal(body)
	str := strings.NewReader(string(byte1))
	fmt.Println("\n上传网址\n上传的数据是", 上传网址, string(byte1))
	req, _ := http.NewRequest("POST", 上传网址, str)
	req.Header.Set("authori-zation", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	resp, err := (&http.Client{}).Do(req)
	if err != nil {
		fmt.Println("qay")
		return
	}
	defer resp.Body.Close()
	var serviceResp map[string]interface{}
	respByte, _ := ioutil.ReadAll(resp.Body)
	json.Unmarshal(respByte, &serviceResp) //第二个参数要地址传递
	fmt.Println("serviceResp", serviceResp)
}
